<?php
namespace app\index\controller;

use think\Controller;
use think\Validate;
use app\index\model\AuthRuleModel;
use app\index\model\AuthGroupModel;
use app\index\model\UsersModel;
use app\index\model\AuthGroupAccessModel;
use app\index\model\AdminNavModel;
use app\common\controller\BaseController;

class Auth extends BaseController
{
    protected $beforeActionList = [
        'isLogin'
    ];

    protected function isLogin(){
        if(!session("username")){
            return $this->redirect('/index.php/index/index/login');
        }
    }

    /*******************权限**********************/
    public function index()
    {
        $model = new AuthRuleModel();
        $data=$model->getTreeData('tree','id','title');
        $assign=array(
            'data'=>$data
        );
        $this->assign($assign);
        return $this->fetch();
    }
    /**
     * 添加权限
     */
    public function add(){
        $model = new AuthRuleModel();
        $data=Input('post.');
        unset($data['id']);
        $data['name'] = strtolower($data['name']);
        $result=$model->addData($data);
        if ($result) {
            return $this->success('添加成功','/index.php/index/auth/index');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
     * 修改权限
     */
    public function edit(){
        $model = new AuthRuleModel();
        $data=Input('post.');
        $map=array(
            'id'=>$data['id']
        );
        $result=$model->editData($map,$data);
        if ($result) {
            return $this->success('修改成功','/index.php/index/auth/index');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
     * 删除权限
     */
    public function delete(){
        $id=Input('get.id');
        $map=array(
            'id'=>$id
        );
        $model = new AuthRuleModel();
        $result=$model->deleteData($map);
        if($result){
            return $this->ajaxReturn(200,null,'删除成功');
        }else{
            return $this->ajaxReturn(400,null,'删除失败');
        }

    }

    public function getRules(){
        $model = new AuthRuleModel();
        $data = $model
            ->order("id")
            ->select();
        return $this->ajaxReturn(200,$data,"查询成功");
    }

    public function updateRules(){
        $id = input("post.id");
        $rules = (input("post.rules"));
        $model = new AuthGroupModel();
        $model->rules = $rules;
        $data = $model->where('id',$id)
            ->update(['rules'=>$rules]);
        return $this->ajaxReturn(200,$data,"修改成功");
    }

    public function getRulesGroupId(){
        $group_id = input("get.group_id");

        $model = new AuthGroupModel();

        $data = $model->where('id',$group_id)
            ->field('rules,title')
            ->find();
        return $this->ajaxReturn(200,$data,"查询成功");
    }

    /*******************菜单管理**********************/
    public function menu()
    {
        $model = new AdminNavModel();
        $data=$model->getTreeData('tree','id','name');
        $assign=array(
            'data'=>$data
        );
        $this->assign($assign);
        return $this->fetch();
    }
    /**
     * 添加权限
     */
    public function menu_add(){
        $model = new AdminNavModel();
        $data=Input('post.');
        unset($data['id']);
        $result=$model->addData($data);
        if ($result) {
            return $this->success('添加成功','/index.php/index/auth/menu');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
     * 修改权限
     */
    public function menu_edit(){
        $model = new AdminNavModel();
        $data=Input('post.');
        $map=array(
            'id'=>$data['id']
        );
        $result=$model->editData($map,$data);
        if ($result) {
            return $this->success('修改成功','/index.php/index/auth/menu');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
     * 删除权限
     */
    public function menu_delete(){
        $id=Input('get.id');
        $map=array(
            'id'=>$id
        );
        $model = new AdminNavModel();
        $result=$model->deleteData($map);
        if($result){
            return $this->ajaxReturn(200,null,'删除成功');
        }else{
            return $this->ajaxReturn(400,null,'删除失败');
        }

    }

    /*******************用户组**********************/
    public function group(){
        $model = new AuthGroupModel();
        $data=$model->select();
        $assign=array(
            'data'=>$data
        );
        $this->assign($assign);
        return $this->fetch();
    }

    /**
     * 添加用户组
     */
    public function add_group(){
        $data=Input('post.');
        unset($data['id']);
        $model = new AuthGroupModel();
        $result=$model->addData($data);
        if ($result) {
            return $this->success('添加成功','/index.php/index/auth/group');
        }else{
            return $this->error('添加失败');
        }
    }

    /**
     * 修改用户组
     */
    public function edit_group(){
        $data=Input('post.');
        $map=array(
            'id'=>$data['id']
        );
        $model = new AuthGroupModel();
        $result=$model->editData($map,$data);
        if ($result) {
            return $this->success('修改成功','/index.php/index/auth/group');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
     * 删除用户组
     */
    public function delete_group(){
        $id=Input('get.id');
        $map=array(
            'id'=>$id
        );
        $model = new AuthGroupModel();
        $result=$model->deleteData($map);
        if($result){
            return $this->ajaxReturn(200,null,'删除成功');
        }else{
            return $this->ajaxReturn(400,null,'删除失败');
        }
    }

    //*****************权限-用户组*****************
    /**
     * 分配权限
     */
    public function rule_group(){
        return $this->fetch();
    }

    //******************用户-用户组*******************
    /**
     * 添加成员
     */
    public function check_user(){
        $username=Input('get.username','');
        $group_id=Input('get.group_id');
        $model = new AuthGroupModel();
        $AGAmodel = new AuthGroupAccessModel();
        $Umodel = new UsersModel();
        $map['id'] = $group_id;
        $group_name=$model->where($map)->field('title')->find();
        $uids=$AGAmodel->getUidsByGroupId($group_id);
        // 判断用户名是否为空
        if(empty($username)){
            $user_data='';
        }else{
            $m['username'] = array('like','%'.$username.'%');
            $user_data=$Umodel->where($m)->select();
        }
        $assign=array(
            'group_name'=>$group_name['title'],
            'uids'=>implode(",",$uids),
            'user_data'=>$user_data,
            'group_id'=>$group_id
        );
        $this->assign($assign);
        return $this->fetch();
    }

    /**
     * 添加用户到用户组
     */
    public function add_user_to_group(){
        $data=Input('get.');
        $map=array(
            'uid'=>$data['uid'],
            'group_id'=>$data['group_id']
        );
        $AGAmodel = new AuthGroupAccessModel();
        $count=$AGAmodel->where($map)->count();
        if($count==0){
            $AGAmodel->addData($data);
        }
        return $this->ajaxReturn(200,null,'操作成功');
    }

    /**
     * 将用户移除用户组
     */
    public function delete_user_from_group(){
        $map=Input('get.');
        $AGAmodel = new AuthGroupAccessModel();
        $result=$AGAmodel->deleteData($map);
        if ($result) {
            $this->success('操作成功','');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 添加管理员
     */
    public function add_admin(){
        $data=Input('post.');
        $rule = [
            'username' =>'require|max:20',
            'password' =>'require|max:16',
            'phone' =>'length:11|number',
        ];
        $checkData =[
            'username' =>$data['username'],
            'password' =>$data['password'],
            'phone' =>$data['phone'],
        ];
        $msg = [
            'username.require' => '用户名不能为空',
            'username.max' => '用户名不能超过20位',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过16位',
            'phone.length' => '电话号码11位',
            'phone.number' => '电话号码是数字',
        ];
        $validate = new Validate($rule,$msg);
        if (!$validate->check($checkData)){
            return $this->error($validate->getError(),'/index.php/index/auth/users_list');
        }
        $Umodel = new UsersModel();
        $AGAmodel = new AuthGroupAccessModel();
        $result=$Umodel->allowField(true)->addData($data);
        if($result){
            if (!empty($data['group_ids'])) {
                $group = array();
                foreach ($data['group_ids'] as $k => $v) {
                    array_push($group,array(
                        'uid'=>$result,
                        'group_id'=>$v
                    ));
                }
                $AGAmodel->addDatas($group);
            }
            // 操作成功
            $this->success('添加成功','/index.php/index/auth/users_list');
        }else{
            $error_word=$Umodel->getError();
            // 操作失败
            $this->error($error_word);
        }
    }

    /**
     * 修改管理员
     */
    public function edit_admin(){
        $data=Input('post.');
        $rule = [
            'username' => 'require|max:20',
            'password' => 'require|max:16',
            'phone' => 'length:11|number',
        ];
        $checkData = [
            'username' => $data['username'],
            'password' => $data['password'],
            'phone' => $data['phone'],

        ];
        $msg = [
            'username.require' => '用户名不能为空',
            'username.max' => '用户名不能超过20位',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过16位',
            'phone.length' => '请输入正确的手机号码',
            'phone.number' => '请输入正确的手机号码',

        ];
        $validate = new Validate($rule,$msg);
        if (!$validate->check($checkData)) {
            return $this->error($validate->getError(),'/index.php/index/auth/users_list');
        }

        $Umodel = new UsersModel();
        $AGAmodel = new AuthGroupAccessModel();
        if(Input('?post.group_ids')){
            $group_ids = $data['group_ids'];
            unset($data['group_ids']);
        }else{
            $AGAmodel->where('uid',$data['id'])->delete();
        }
        $Umodel->editData($data['id'],$data);
        if (!empty($group_ids)) {
            $group = array();
            $AGAmodel->where('uid',$data['id'])->delete();
            foreach ($group_ids as $k => $v) {
                array_push($group,array(
                    'uid'=>$data['id'],
                    'group_id'=>$v
                ));
            }
            $AGAmodel->addDatas($group);
        }
        // 操作成功
        $this->success('修改成功','/index.php/index/auth/users_list');
    }


    /*******************用户列表**********************/
    public function users_list(){
        $word=Input('get.word','');
        if (empty($word)) {
            $map=array();
        }else{
            $map=array(
                'username'=>$word);
        }
        $model = new AuthGroupAccessModel();
        $data=$model->getAllData();

        //获取组
        $gmodel = new AuthGroupModel();
        $group = $gmodel->select();

        $assign=array(
            'data'=>$data,
            'group' => $group
        );
        $this->assign($assign);
        return $this->fetch('admin_user_list');
    }



}
